package com.yonyou.isv.demo.openapi.base.datacenter.impl;

import com.yonyou.isv.demo.openapi.base.properties.OpenApiProperties;
import com.yonyou.isv.demo.openapi.base.datacenter.DataCenterUrlProvider;
import com.yonyou.isv.demo.openapi.base.datacenter.pojo.GatewayAddressResponse;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author nishch
 * @description: TODO
 * @date 2022/3/8
 */
public abstract class DataCenterUrlProviderImpl implements DataCenterUrlProvider {

    @Resource
    @Getter
    RestTemplate restTemplate;
    @Value("${spring.profiles.active}")
    private String active;
    @Resource
    OpenApiProperties properties;

    /**
     * 当前环境是否支持多数据中心
     * @return boolean
     */
    private boolean moreDataCenter(){
        String[] supportDataCenterEnv = new String[]{
            "production",
            "sandbox"
        };
        return Arrays.asList(supportDataCenterEnv).contains(active);
    }

    @Override
    public String buildBusinessUrl() {
        return useGatewayAddress().getGatewayUrl();
    }

    @Override
    public String buildTokenUrl() {
        return useGatewayAddress().getTokenUrl();
    }

    private GatewayAddressResponse.GatewayAddressDTO useGatewayAddress(){
        GatewayAddressResponse.GatewayAddressDTO gatewayAddressDTO= null;
        if(moreDataCenter()){
            gatewayAddressDTO = queryGatewayAddress();
        }else{
            gatewayAddressDTO = new GatewayAddressResponse.GatewayAddressDTO(properties.getGatewayAddressUrl(),properties.getGatewayAddressUrl());
        }
        return gatewayAddressDTO;
    }

    @Override
    public String queryTenantId() {
        return properties.getTenantId();
    }
}
